package com.demo.petshop.service.impl;

import com.demo.petshop.entity.*;
import com.demo.petshop.mapper.*;
import com.demo.petshop.service.VideosService;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.sqlite.date.DateFormatUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.demo.petshop.entity.table.StoreFollowersTableDef.STORE_FOLLOWERS;
import static com.demo.petshop.entity.table.StoresTableDef.STORES;
import static com.demo.petshop.entity.table.UsersTableDef.USERS;
import static com.demo.petshop.entity.table.VideoCommentsTableDef.VIDEO_COMMENTS;
import static com.demo.petshop.entity.table.VideoLikesTableDef.VIDEO_LIKES;
import static com.demo.petshop.entity.table.VideoProductsTableDef.VIDEO_PRODUCTS;
import static com.demo.petshop.entity.table.VideoTagRelationTableDef.VIDEO_TAG_RELATION;
import static com.demo.petshop.entity.table.VideoTagsTableDef.VIDEO_TAGS;
import static com.demo.petshop.entity.table.VideosTableDef.VIDEOS;
import static com.demo.petshop.entity.table.ProductsTableDef.PRODUCTS;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-06-11
 */
@Service
public class VideosServiceImpl extends ServiceImpl<VideosMapper, Videos> implements VideosService {

    @Autowired
    private VideosMapper videosMapper;

    @Autowired
    private VideoTagsMapper videoTagsMapper;

    @Autowired
    private VideoCommentsMapper videoCommentsMapper;

    @Autowired
    private VideoTagRelationMapper videoTagRelationMapper;

    @Autowired
    private VideoProductsMapper videoProductsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private VideoLikesMapper videoLikesMapper;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object getCategories() {
        return Result.success(videoTagsMapper.selectAll());
    }

    @Override
    public Object getList(Map<String, Object> params) {
        String query = "query";
        String category = "category";
        // 使用 QueryWrapper.create() 来构建一个干净的查询
        QueryWrapper queryWrapper = QueryWrapper.create()
                // 1. 只查询 Videos 表的所有字段，并去重
                .select(VIDEOS.ALL_COLUMNS)
                .from(VIDEOS)
                // 2. 使用 LEFT JOIN 连接表，更清晰、更标准
                .leftJoin(VIDEO_TAG_RELATION).on(VIDEOS.VIDEO_ID.eq(VIDEO_TAG_RELATION.VIDEO_ID))
                .leftJoin(VIDEO_TAGS).on(VIDEO_TAG_RELATION.TAG_ID.eq(VIDEO_TAGS.TAG_ID))
                //3. 处理分类筛选 (如果存在)
                .where(VIDEO_TAGS.TAG_ID.eq(params.get(category))
                        .when(params.get(category) != null && !"".equals(params.get(category))))
                // 4. 处理搜索词 (关键的 OR 逻辑)
                .and(VIDEOS.TITLE.like(params.get(query))
                        .or(VIDEOS.DESCRIPTION.like(params.get(query)))
                        // 5. 搜索的是标签的名称，而不是ID
                        .or(VIDEO_TAGS.NAME.like(params.get(query)))
                        .when(params.get(query) != null && !"".equals(params.get(query))))
                .groupBy(VIDEOS.VIDEO_ID)
                .orderBy(VIDEOS.VIDEO_ID, false);
        List<Videos> videos = videosMapper.selectListByQuery(queryWrapper);
        for (Videos videos1:videos){
            QueryWrapper queryWrapper1=new QueryWrapper();
            queryWrapper1.select(USERS.ALL_COLUMNS).from(USERS)
                    .where(USERS.USER_ID.eq(videos1.getAuthorId()));
            Users users = usersMapper.selectOneByQuery(queryWrapper1);
            videos1.setAuthorName(users.getUsername());
        }
        return Result.success(videos);
    }

    @Override
    public Object listStore(Integer storeId) {
        return Result.success(videosMapper.selectListByQuery(new QueryWrapper()
                        .select(VIDEOS.ALL_COLUMNS)
                        .from(VIDEOS)
                        .leftJoin(VIDEO_PRODUCTS).on(VIDEOS.VIDEO_ID.eq(VIDEO_PRODUCTS.VIDEO_ID))
                        .leftJoin(PRODUCTS).on(VIDEO_PRODUCTS.PRODUCT_ID.eq(PRODUCTS.PRODUCT_ID))
                        .where(PRODUCTS.STORE_ID.eq(storeId))
                        .groupBy(VIDEOS.VIDEO_ID)
                ));
    }

    @Override
    public Object updateProducts(Map<String, Object> params) {
        int videoId = (int) params.get("videoId");
        List<Integer> productIds = (List<Integer>) params.get("productIds");
        videoProductsMapper.deleteByQuery(new QueryWrapper().where(VIDEO_PRODUCTS.VIDEO_ID.eq(videoId)));
        for(int productId : productIds){
            VideoProducts videoProducts = new VideoProducts();
            videoProducts.setVideoId(videoId);
            videoProducts.setProductId(productId);
            videoProductsMapper.insert(videoProducts);
        }
        return Result.success("更新成功");
    }

    @Override
    public Object getTags() {
        return Result.success(videoTagsMapper.selectAll());
    }

    @Override
    public Object getVideo(Integer videoId) {
        return Result.success(videosMapper.selectOneById(videoId));
    }

    @Override
    public Object getComments(Integer videoId) {
        return Result.success(videoCommentsMapper.selectListByQuery(new QueryWrapper()
                .where(VIDEO_COMMENTS.VIDEO_ID.eq(videoId))
                .orderBy(VIDEO_COMMENTS.CREATED_AT, false)));
    }

    @Override
    public Object getRecommended(Integer videoId) {
        return Result.success(videosMapper.selectListByQuery(new QueryWrapper()
                .orderBy(VIDEOS.VIEWS, false)
                .limit(5)));
    }

    @Override
    public Object addViewer(Integer videoId) {
        Videos video = videosMapper.selectOneById(videoId);
        video.setViews(video.getViews() + 1);
        return Result.success(videosMapper.update(video));
    }

    @Override
    @Transactional
    public Object uploadVideo(VideoUploadDTO videoUploadDTO) {

        if (videoUploadDTO.getVideo() == null || videoUploadDTO.getVideo().isEmpty()) {
            return Result.fail("视频数据不能为空");
        }
        if (videoUploadDTO.getTitle() == null || videoUploadDTO.getTitle().trim().isEmpty()) {
            return Result.fail("视频标题不能为空");
        }

        Videos videoEntity = new Videos();
        videoEntity.setTitle(videoUploadDTO.getTitle());
        videoEntity.setDescription(videoUploadDTO.getDescription());

        // [核心逻辑] 将Base64编码的字符串存入现有的 `_url` 和 `_image` 字段
        videoEntity.setVideoUrl(videoUploadDTO.getVideo()); // 将视频Base64存入 video_url
        videoEntity.setCoverImage(videoUploadDTO.getCoverImage()); // 将封面Base64存入 cover_image

        videoEntity.setAuthorId(getUserId());
        videoEntity.setCreatedAt(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        videoEntity.setViews(0);
        videoEntity.setCommentsCount(0);
        videoEntity.setShareCount(0);
        videoEntity.setDuration(videoUploadDTO.getDuration());
        videoEntity.setLikes(0);

        videosMapper.insert(videoEntity);
        videoEntity = videosMapper.selectOneByQuery(new QueryWrapper()
                .where(VIDEOS.AUTHOR_ID.eq(getUserId()))
                .orderBy(VIDEOS.VIDEO_ID, false)
                .limit(1));
        Integer newVideoId = videoEntity.getVideoId();

        List<Integer> tagIds = videoUploadDTO.getTags();
        tagIds.add(1);
        for (Integer tagId : tagIds) {
            VideoTagRelation tagRelation = new VideoTagRelation();
            tagRelation.setVideoId(newVideoId);
            tagRelation.setTagId(tagId);
            videoTagRelationMapper.insert(tagRelation);
        }

        List<Integer> productIds = videoUploadDTO.getProducts();
        if (productIds != null && !productIds.isEmpty()) {
            for (Integer productId : productIds) {
                VideoProducts productRelation = new VideoProducts();
                productRelation.setVideoId(newVideoId);
                productRelation.setProductId(productId);
                videoProductsMapper.insert(productRelation);
            }
        }

        // 6. 返回成功响应
        return Result.success("视频上传成功！Base64数据已存入数据库。");
    }

    @Override
    public Object delete(Integer videoId) {
        videoLikesMapper.deleteByQuery(new QueryWrapper().where(VIDEO_LIKES.VIDEO_ID.eq(videoId)));
        videoProductsMapper.deleteByQuery(new QueryWrapper().where(VIDEO_PRODUCTS.VIDEO_ID.eq(videoId)));
        videoTagRelationMapper.deleteByQuery(new QueryWrapper().where(VIDEO_TAG_RELATION.VIDEO_ID.eq(videoId)));
        videoCommentsMapper.deleteByQuery(new QueryWrapper().where(VIDEO_COMMENTS.VIDEO_ID.eq(videoId)));
        return Result.success(videosMapper.deleteById(videoId));
    }

    @Override
    public Object listByMemberLevel() {
        Users user = usersMapper.selectOneById(getUserId());
        if("-1".equals(user.getMemberLevel())){
            return Result.success(videosMapper.selectListByQuery(new QueryWrapper()
                    .select(VIDEOS.ALL_COLUMNS)
                    .from(VIDEOS)
                    .leftJoin(VIDEO_PRODUCTS).on(VIDEOS.VIDEO_ID.eq(VIDEO_PRODUCTS.VIDEO_ID))
                    .leftJoin(PRODUCTS).on(VIDEO_PRODUCTS.PRODUCT_ID.eq(PRODUCTS.PRODUCT_ID))
                    .leftJoin(STORES).on(PRODUCTS.STORE_ID.eq(STORES.STORE_ID))
                    .leftJoin(STORE_FOLLOWERS).on(STORES.STORE_ID.eq(STORE_FOLLOWERS.STORE_ID))
                    .where(STORE_FOLLOWERS.USER_ID.eq(getUserId()))
                    .groupBy(VIDEOS.VIDEO_ID)
            ));
        }
        return Result.success(videosMapper.selectAll());
    }
}
